package com.pig4cloud.ila.client.websocket;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.common.security.annotation.Inner;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Inner(value = false)
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
	private static AtomicInteger onlineNum = new AtomicInteger();
	private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

	public void sendMessage(Session session, String message) throws IOException {
		if (session != null) {
			synchronized (session) {
				session.getBasicRemote().sendText(message);
			}
		}
	}

	public void broadcast(String message) {
		for (Session session : sessionPools.values()) {
			try {
				sendMessage(session, message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void notify(String userName, String message) throws IOException {
		Session session = sessionPools.get(userName);
		sendMessage(session, message);
	}

	@OnOpen
	public void onOpen(Session session, @PathParam(value = "sid") String userName) {
		sessionPools.put(userName, session);
		broadcast("110");
		System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
	}

	@OnClose
	public void onClose(@PathParam(value = "sid") String userName) {
		sessionPools.remove(userName);
		subOnlineCount();
		System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
	}

	@OnMessage
	public void onMessage(String message) {
		broadcast(message);
	}

	@OnError
	public void onError(Session session, Throwable throwable) {
		System.out.println("发生错误");
		throwable.printStackTrace();
	}

	public static void addOnlineCount() {
		onlineNum.incrementAndGet();
	}

	public static void subOnlineCount() {
		onlineNum.decrementAndGet();
	}
}
